package leecode.q39.q39good;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 2021年8月16日23:59:20 开始
 * 2021年8月17日00:12:18 结束
 */
public class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> list = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        traceBack(candidates, target, 0);
        return res;
    }

    private void traceBack(int[] candidates, int target, int sumCur) {
        if (sumCur > target || isDup(list)) {
            return;
        }
        if (sumCur == target) {
            res.add(new ArrayList<>(list));
        }
        for (int i = 0; i < candidates.length && (sumCur + candidates[i] <= target); i++) {//剪枝动作
            int cur = candidates[i];
            sumCur += cur;
            list.add(cur);
            traceBack(candidates, target, sumCur);
            list.remove(list.size() - 1);
            sumCur -= cur;
        }
    }

    private boolean isDup(List<Integer> list) {
        if (list.size() <= 1) {
            return false;
        }
        return list.get(list.size() - 1) < list.get(list.size() - 2);
    }
}
